import os
from PyCmpltrtok.common import get_dir_name_ext

# Below proves the DLL library is needed beside the compiled CFFI Python module.

xdir, xbase, xext = get_dir_name_ext(os.path.abspath(__file__))
xlib_dir = os.path.dirname(xdir)
NAME = 'LD_LIBRARY_PATH'

# USELESS !! See below !!
ldp = os.environ.get(NAME, '.')
if not ldp:
    os.environ[NAME] = xlib_dir
else:
    os.environ[NAME] = f'{xlib_dir}:{xdir}:{os.environ[NAME]}'
print(os.environ[NAME])

# Env various still needed to export in shell!!
# export LD_LIBRARY_PATH="/home/peiyp2004/code/python_basic/study/python_cookbook/ch15_c_ext:$LD_LIBRARY_PATH"
print(f'export {NAME}="{xlib_dir}:{xdir}${{LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}}"')
    
from _sample_cffi import ffi, lib as sample

if '__main__' == __name__:
    
    from PyCmpltrtok.common import get_dir_name_ext, sep
    from typing import List
    import array
    import numpy as np
    import ctypes
    
    sep('gcd')
    x = 60
    y = 24
    r = sample.gcd(x, y)
    print(f'gcd({x}, {y}) = {r}')
    
    sep('in_mandel')
    pairs = [
        [0, 0],
        [-0.74543, 0.11301],
        [-1.4011, 0.60206],
        [1, 1],
        [2, 2],
    ]
    n = 3
    for p in pairs:
        print(f'n={n}', p, '->', sample.in_mandel(p[0], p[1], n))
        
    sep('divide')
    x = 20
    y = 7
    remainder = ffi.new('int *')
    quotient = sample.divide(x, y, remainder)
    print(f'divide({x}, {y}) -> {quotient}, {remainder[0]}')
    
    sep('avg')
    sep('array.array')
    values = array.array('d', [1, 2, 3, 4, 5])
    ptr = ffi.cast('double *', values.buffer_info()[0])
    print(values, sample.avg(ptr, len(values)))
    
    sep('list')
    values = [1, 2, 3, 4, 5]
    print(values, sample.avg(values, len(values)))
    
    sep('tuple')
    values = (1, 2, 3, 4, 5)
    print(values, sample.avg(values, len(values)))
    
    sep('np.ndarray')
    values = np.array([1, 2, 3, 4, 5], dtype=float)
    ptr = ffi.cast('double *', values.ctypes.data)
    print(values, sample.avg(ptr, len(values)))
    
    sep('distance')
    p1 = ffi.new('Point *')
    p1.x = 1
    p1.y = 1
    p2 = ffi.new('Point *')
    p2.x = 4
    p2.y = 5
    print(p1.x, p1.y, ';', p2.x, p2.y, '->', sample.distance(p1, p2))
    print(p1.x, p1.y, ';', p2.x, p2.y, '->', sample.distance_my(p1[0], p2[0]))
